package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.SMSLogAdapter;
import vn.personal.anhht.bloback12.bean.SMSLogObject;
import vn.personal.anhht.bloback12.widget.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class TabLogSMSActivity extends Activity{
	
	private SMSLogAdapter adapterSms;
	private ListView lvSms;
	private ArrayList<SMSLogObject> listSmsLog = new ArrayList<SMSLogObject>();
	ProgressDialog dialog;
	private Resources rs;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//LocalizationUtil.setupLanguage(getApplicationContext());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_log_sms);
		rs = getResources();
		ActionBar actionBar = (ActionBar)findViewById(R.id.actionbar);
        actionBar.setVisibility(View.GONE);
		Log.e("LOGSMS TAB", "LOGSMS TAB");
		initLogSMS();
	}
	
	public void initLogSMS(){
		dialog = new ProgressDialog(this);
		adapterSms = new SMSLogAdapter(getApplicationContext(),
				android.R.layout.simple_list_item_1, listSmsLog);
		lvSms = (ListView) findViewById(R.id.lvsmslog);
		new GetSMSThread().execute();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mn_filter, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.item_filter_back: {
			// back(RESULT_OK);
			break;
		}
		case R.id.item_filter_clear: {		
			displayDialog();
			break;

		}
		default:
			super.onOptionsItemSelected(item);
		}
		return true;
	}
	
	public void refresh() {
		listSmsLog.clear();
		new GetSMSThread().execute();
	}
	
	public void displayDialog(){
		//final String word = listWords.get(position);
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(getResources().getString(R.string.history_alert_title));
		alert.setMessage(getResources().getString(R.string.history_alert_msg));
		alert.setPositiveButton(getResources().getString(R.string.ok) , new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				deleteMessageLog();
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.history_toast_delok),
						Toast.LENGTH_LONG).show();
				refresh();
			}
		});

		alert.setNegativeButton(getResources().getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		alert.show();
	}
	
	
	/*
	 * AnhHT:
	 */
	public int deleteMessageLog() {
		Uri deleteUri = Uri.parse("content://sms");
		int count = 0;
		Cursor c = getApplicationContext().getContentResolver().query(
				deleteUri, null, null, null, null);
		while (c.moveToNext()) {
			try {
				String pid = c.getString(0); // Get id;
				String uri = "content://sms/" + pid;
				count = getApplicationContext().getContentResolver()
						.delete(Uri.parse(uri), null, null);
			} catch (Exception e) {
			}
		}
		c.close();
		return count;
	}
	
	/* ========================Get List SMS============================= */
	private class GetSMSThread extends
			AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			loadSMSToList();
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.setMessage(rs.getString(R.string.bl_dialog_load));
			dialog.show();
		}

		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			lvSms.setAdapter(adapterSms);
		}

		private void loadSMSToList() {
			String[] strFields = { "_id", "address", "person", "date", "body" };
			String WHERE_CONDITION = null;
			String SORT_ORDER = "date DESC";
			Cursor cursor = getApplicationContext().getContentResolver().query(
					Uri.parse("content://sms"), strFields, WHERE_CONDITION,
					null, SORT_ORDER);
			if (cursor.moveToFirst()) {
				int indexOfAddress = cursor.getColumnIndex("address");
				int indexOfBody = cursor.getColumnIndex("body");
				int indexOfTime = cursor.getColumnIndex("date");
				do {
					SMSLogObject smsob = new SMSLogObject();
					String phone = cursor.getString(indexOfAddress);
					smsob.setPhone(phone);
					String name = getContactNameFromNumber(phone);
					smsob.setName(name);
					String message = cursor.getString(indexOfBody);
					smsob.setMessage(message);
					String date = cursor.getString(indexOfTime);
					smsob.setTime(date);
					listSmsLog.add(smsob);
				} while (cursor.moveToNext());
				
			}
			cursor.close();
		}
		private String getContactNameFromNumber(String number) {
			String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };
			Uri contactUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI,
					Uri.encode(number));
			Cursor c = getContentResolver().query(contactUri, projection, null,
					null, null);
			if (c.moveToFirst()) {
				String name = c.getString(c.getColumnIndex(Phone.DISPLAY_NAME));
				return name;
			}
			c.close();
			return number;
		}
	}
}
